package com.leetcode.dataStruct.tree;

import com.leetcode.dataStruct.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class BuildTree {

    Map<Integer, Integer> indexMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = preorder.length;
        for (int i = 0; i < n; i++) {
            indexMap.put(inorder[i], i);
        }
        return build(preorder, inorder, 0, n - 1, 0, n - 1);
    }

    private TreeNode build(int[] preorder, int[] inorder, int preLeft,
                           int preRight, int inLeft, int inRight) {
        if (preLeft > preRight) {
            return null;
        }
        int inRoot = indexMap.get(preorder[preLeft]);
        TreeNode root = new TreeNode(preorder[preLeft]);
        int leftTreeSize = inRoot - inLeft;
        root.left = build(preorder, inorder, preLeft + 1,
                preLeft + leftTreeSize, inLeft, inRoot - 1);
        root.right = build(preorder, inorder, preLeft + leftTreeSize + 1, preRight,
                inRoot + 1, inRight);
        return root;
    }
}
